package com.sxyc.tintin.model;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.amitek.service.bean.RemoteException;
import com.amitek.service.bean.ServiceException;
import com.amitek.service.bean.protocol.PosInfo;
import com.amitek.service.bean.protocol.TrackInfo;
import com.amitek.service.bean.response.TrackDesc;
import com.amitek.service.bean.response.TrackList;
import com.amitek.service.bean.response.TrackStatus;
import com.amitek.service.service.ServiceFactory;
import com.amitek.service.service.ServiceInstance;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;


public class Drivingrange extends Model<Drivingrange> {

	private static final long serialVersionUID = 1L;

	public static final Drivingrange dao = new Drivingrange();

	// 使用jFinal 日志
	private com.jfinal.log.Log log = com.jfinal.log.Log.getLog(this.getClass());

	
	//获取用户里程排行
	public Record getDrivingrange(long deviceId,String openid){
		Record record =Db.findFirst(
				"select t.*,w.NickName,w.HeadImgurl from (select @rownum:=@rownum+1 AS rownum,Deviceid,TodayRange,TodayDate,`Range` from drivingrange,(SELECT @rownum:=0) r where Deviceid is not null ORDER BY TodayRange desc) t LEFT JOIN devicebinding d ON t.Deviceid = d.DeviceId LEFT JOIN wx_user w ON w.OpenId = d.OpenId where t.Deviceid= ? ",
				 new Object[] { deviceId });
		if(record==null){
			saveNewDrivingRange(deviceId,openid, 0, 0, new Date().getTime(), 0, 0);
			getDrivingrange(deviceId,"");
		}else{
		record.set("rownum", (int)(record.getDouble("rownum")/1));
		record.set("TodayDate", (int)(record.getDouble("TodayDate")/1));
		record.set("TodayRange", (int)(record.getDouble("TodayRange")/1));
		}
		return record;
	}
	
	//获取排行前几名
	public List<Record> getRanges() {
		List<Record> persons = Db.find("select @rownum:=@rownum+1 AS num, Deviceid, headImg, NickName, TodayRange from (select d.Deviceid, w.HeadImgurl as headImg, w.NickName, d.TodayRange from drivingrange d LEFT JOIN devicebinding b on d.Deviceid = b.DeviceId LEFT JOIN wx_user w ON w.OpenId = b.OpenId where d.Deviceid is not null ORDER BY d.TodayRange desc limit 10) u, (select @rownum:=0) r");
		for (Record record : persons) {
			record.set("num", (int)(record.getDouble("num")/1));
			record.set("TodayRange", (int)(record.getDouble("TodayRange")/1));
		}
		System.out.println("test");
		return persons;
	}

	//获取行为分析数据
	public Record getDrivingrange(String openId,long deviceid){
		Record record =Db.findFirst("select `Range`, TodayRange, TodayDate, accelerateCnt, decelerateCnt from drivingrange where openId= ? ",
				 new Object[] { openId });
		if(record==null){
			saveNewDrivingRange(deviceid,openId, 0, 0, new Date().getTime(), 0, 0);
			getDrivingrange(openId,deviceid);
		}else{
		record.set("Range", (int)(record.getDouble("Range")/1));
		record.set("TodayDate", (int)(record.getDouble("TodayDate")/1));
		record.set("TodayRange", (int)(record.getDouble("TodayRange")/1));
		}
		return record;
	}
	
	//清零总里程
	public void clear0(String openId){
		Drivingrange range =Drivingrange.dao.findFirst("select id from drivingrange where openId= ? ",
				 new Object[] { openId });
		System.out.println(range.set("range", 0).update());
//		Db.delete("drivingrange", new Record().set("openid", openId));
	}
		
	//定时清零每日里程和时间
	public void clearTask() {
		log.info("清零开始啦！");
		Db.update("update drivingrange set TodayRange = 0, TodayDate = 0");
	}
	
	/**
	 * 初始化行为分析数据
	 */
	public void saveNewDrivingRange(long deviceId, String openId,double range, long date, long lastdate, double todayRange, long todayDate){
		JSONObject weekday = new JSONObject();
		JSONObject weekdaydate = new JSONObject();
		weekday.put("周一", 0);
		weekday.put("周二", 0);
		weekday.put("周三", 0);
		weekday.put("周四", 0);
		weekday.put("周五", 0);
		weekday.put("周六", 0);
		weekday.put("周日", 0);
		weekdaydate.put("周一", 0);
		weekdaydate.put("周二", 0);
		weekdaydate.put("周三", 0);
		weekdaydate.put("周四", 0);
		weekdaydate.put("周五", 0);
		weekdaydate.put("周六", 0);
		weekdaydate.put("周日", 0);
		new Drivingrange().set("DeviceId", deviceId)
							.set("Openid", openId)
							.set("Range", range)
							.set("Date", date)
							.set("LastDate", lastdate)
							.set("WeekdayRange", weekday.toString())
							.set("WeekdayDate", weekdaydate.toString())
							.set("TodayRange", todayRange)
							.set("TodayDate", todayDate)
							.save();
	}
	
	/**
	 * 
	 */
	public List<Object> getTrackRange(long deviceid, long recordStart, long recordStop){
		if(recordStart == 0){
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			recordStart = calendar.getTimeInMillis();
		}
		if(recordStop == 0){
			recordStop = Calendar.getInstance().getTimeInMillis();
		}
		double range = 0;//总行程行驶里程	(单位：公里)
		long date = 0;//总行程时间			(单位：分)
		int size = 0;//行程数
		//查询设备历史数据
		TrackList list = getTrackInfo(deviceid, recordStart, recordStop);
		if(list != null) {//如果返回值为空，跳过本次操作
			for (TrackDesc trackDesc : list) {
				System.out.println(trackDesc);
				//查询每一段行程信息
				TrackStatus status = getTrackStatus(trackDesc.deviceId, trackDesc.trackId);
				TrackInfo info = status.trackInfo;
				int mileage = 0;
				if(info != null)
					mileage = info.totalMileage;
				if(mileage > 100){//如果行驶里程大于100米，则记录，否则忽略不计
					range += mileage;
					date += trackDesc.trackStop - trackDesc.trackStart;
				}
			}
			range = (double)((int)range/100)/10;//单位转换为公里，保留一位小数
			date = date/(60*1000);
			size = list.size();
			System.out.println("range :"+ range +"  date :"+date+"  size :"+size );
		}
		List<Object> res = new ArrayList<Object>();
		res.add(range);
		res.add(date);
		res.add(size);
		return res;
	}
	
	/**
	 * 
	 */
	public TrackStatus getTrackStatus(long clientid,long trackid){
		ServiceInstance serviceInstance = ServiceFactory.getServiceInstance();
		TrackStatus status = null;
		try {
			if(trackid == 0){
				status = serviceInstance.queryTrackStatus(clientid, null);
			}else{
				status = serviceInstance.queryTrackStatus(clientid, trackid);
			}
//			System.out.println(status);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return status;
	}
	
	/**
	 * 
	 */
	public TrackList getTrackInfo(long clientid,long recordStart,long recordStop){
		ServiceInstance serviceInstance = ServiceFactory.getServiceInstance();
		TrackList info = null;
		try {
			info = serviceInstance.queryTrackInfo(clientid, recordStart, recordStop);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			log.error("ServiceException……");
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			log.error("RemoteException……");
			return null;
		}
		return info;
	}
	
	/**
	 * 行为分析 之 周里程
	 */
	public Record getWeekRanges(long deviceId,String openId) {
		Record res = Db.findFirst(
				"select d.WeekdayRange, d.WeekdayDate, d.TodayRange,d.Oil, d.TodayDate, c.CarNo from drivingrange d LEFT JOIN carinfo c ON d.Deviceid = c.DeviceId where d.Deviceid = ?",
					new Object[]{ deviceId });
		DecimalFormat df = new DecimalFormat("#0.0");
		System.out.println(res);
		if(res == null){
			saveNewDrivingRange(deviceId,openId, 0, 0, new Date().getTime(), 0, 0);
			res = Db.findFirst(
					"select d.WeekdayRange, d.WeekdayDate, d.TodayRange,d.Oil, d.TodayDate, c.CarNo from drivingrange d LEFT JOIN carinfo c ON d.Deviceid = c.DeviceId where d.Deviceid = ?",
						new Object[]{ deviceId });
		}
		String json = res.getStr("WeekdayRange");
		String jsondate = res.getStr("WeekdayDate");
		if (json == null) {// 如果周里程为空，创建新的周里程
			json = "{'周一':0,'周二':0,'周三':0,'周四':0,'周五':0,'周六':0,'周日':0}";
			jsondate = "{'周一':0,'周二':0,'周三':0,'周四':0,'周五':0,'周六':0,'周日':0}";
		}
		JSONObject weekday = JSONObject.parseObject(json);
		JSONObject weekdaydate = JSONObject.parseObject(jsondate);
		Calendar calendar = Calendar.getInstance();
		int i = calendar.get(Calendar.DAY_OF_WEEK);
		weekday.put(getWeekday(i), res.getDouble("TodayRange"));
		weekdaydate.put(getWeekday(i), res.getInt("TodayDate"));
		res.set("WeekdayRange", weekday.values());
		res.set("WeekdayDate", weekdaydate.values());
		res.set("oil", df.format((res.getDouble("TodayRange") / 100) *(res.getDouble("Oil"))));// 设置油耗
		res.set("fen", getfen(res.getDouble("TodayRange")));// 设置评分
		return res;
	}

	/**
	 * 里程评分
	 */
	public static int getfen(double r) {
		int fen = 0;
		if (r == 0) {
			fen = 1;
		} else if (r < 15) {
			fen = 50;
		} else if (r < 20) {
			fen = 60;
		} else if (r < 50) {
			fen = 75;
		} else if (r < 70) {
			fen = 79;
		} else if (r < 80) {
			fen = 81;
		} else if (r < 90) {
			fen = 83;
		} else if (r < 100) {
			fen = 84;
		} else if (r < 130) {
			fen = 85;
		} else if (r < 150) {
			fen = 88;
		} else if (r < 170) {
			fen = 89;
		} else if (r < 200) {
			fen = 90;
		} else if (r < 250) {
			fen = 92;
		} else if (r < 300) {
			fen = 94;
		} else if (r < 350) {
			fen = 96;
		} else if (r < 400) {
			fen = 98;
		} else {
			fen = 99;
		}
		return fen;
	}
		
	//获取周一的时间戳
	public long getMonday(int i, long today){
		long monday = 0;
		if(i == 1){//周日-6天
			monday = today-(6*24*60*60*1000);
		}else{//其它-（i-2）天
			monday = today-((i-2)*24*60*60*1000);
		}
		return monday;
			
	}
		
	public String getWeekday(int i){
		String weekday = "";
		switch (i) {
		case -5:
			weekday = "周一";
			break;
		case -4:
			weekday = "周二";
			break;
		case -3:
			weekday = "周三";
			break;
		case -2:
			weekday = "周四";
			break;
		case -1:
			weekday = "周五";
			break;
		case 0:
			weekday = "周六";
			break;
		case 1:
			weekday = "周日";
			break;
		case 2:
			weekday = "周一";
			break;
		case 3:
			weekday = "周二";
			break;
		case 4:
			weekday = "周三";
			break;
		case 5:
			weekday = "周四";
			break;
		case 6:
			weekday = "周五";
			break;
		case 7:
			weekday = "周六";
			break;
		default:
			break;
		}
		return weekday;
	}
	
	public static void main(String[] args) {
		Drivingrange.dao.saveNewDrivingRange(1234556677l,"", 0, 0, new Date().getTime(), 0, 0);
	}

}
